<template>
  <div class="comment_main">
    <h4>发表评论</h4>
    <hr>
    <van-cell-group>
      <van-field v-model="comVal" placeholder="在此输入评论"/>
      <van-button type="info" @click="addComment">提交评论</van-button>
    </van-cell-group>
    <van-list :finished="finished" finished-text="没有更多了">
      <van-cell v-for="(item,index) in commentList" :key="index">
        <div class="comInfo">第{{index+1}}楼 用户:{{item.user_name}} 发表时间:{{item.add_time.slice(0,10)}}</div>
        <div class="comCot">{{item.content}}</div>
      </van-cell>
      <van-button class="jiazai" type="info" @click="getCommentList">加载更多</van-button>
    </van-list>
  </div>
</template>

<script>
export default {
  props: ["id"],
  data() {
    return {
      page: 1,
      commentList: [],
      comVal: "",
      loading: false,
      finished: false
    };
  },
  created() {
    this.getCommentList();
  },
  methods: {
    async getCommentList() {
      console.log(this.id);
      const { data: res } = await this.$http.get(
        `/api/getcomments/${this.id}?pageindex=${this.page}`
      );
      this.page++;
      this.loading = false;
      if (res.message.length === 0) this.finished = true;
      console.log(res);
      //将后面加载的数据往后面添加。避免出现点击加载更多后之前的评论不见的bug
      this.commentList = [...this.commentList, ...Array.from(res.message)];
      // console.log(this.commentList);
    },
    async addComment() {
      const { data: res } = await this.$http.post(
        `/api/postcomment/${this.id}`,
        { content: this.comVal }
      );
      if (res.status !== 0) return this.$toast.fail("评论失败");
      console.log(res);
      this.page = 1;
      this.comVal = "";
      this.loading = false;
      this.commentList = [];
      this.$toast.success("成功发表评论");
      this.getCommentList();
    }
  }
};
</script>

<style scoped lang="less">
.comment_main {
  margin: 10px 10px 0 10px;
}
.van-field {
  height: 100px;
  border: 1px solid #ccc;
}
.van-button {
  width: 100%;
  margin-top: 10px;
  padding: 0 15px;
  font-size: 14px;
  color: #fff;
  background-color: #1989fa;
  border: 1px solid #1989fa;
}
.comInfo {
  background-color: #ccc;
  line-height: 30px;
  font-size: 12px;
  height: 30px;
}
.comCot {
  padding: 5px 10px;
}
.jiazai {
  color: #f44;
  background-color: #fff;
  border: 1px solid #f44;
}
</style>
